package io.bdmc.common.utils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;

public class ByteUtil {

    public static byte[] copyByte(int len, byte[] src, int start) {
        byte[] comm = new byte[len];
        System.arraycopy(src, start, comm, 0, len);
        return comm;
    }

    public static String doubleToString(Double value) {
        BigDecimal b = BigDecimal.valueOf(value).setScale(2, RoundingMode.HALF_DOWN);
        return b.toString();
    }

    public static String HexToStr(String GBKStr) {

        byte[] b = HexToBytes(GBKStr);
        String chineseStr = GBKStr;
        try {
            chineseStr = new String(b, "gbk");
        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        }
        return chineseStr;
    }

    public static byte[] HexToBytes(String hexStr) {
        byte[] b = new byte[hexStr.length() / 2];
        for (int i = 0; i < b.length; i++)
            b[i] = (byte) Integer.parseInt(hexStr.substring(2 * i, 2 * i + 2), 16);
        return b;
    }

    /**
     * 把一个2位的数组转化位整形
     * 
     * @param value
     * @return
     * @throws Exception
     */
    public static int twoBytesToInteger(byte[] value) {
        // if (value.length < 2) {
        // throw new Exception("Byte array too short!");
        // }
        int temp0 = value[0] & 0xFF;
        int temp1 = value[1] & 0xFF;
        return ((temp0 << 8) + temp1);
    }

    public static byte[] hexToBytes(String hex) {
        if (hex == null || hex.equals("")) {
            return null;
        }
        hex = hex.toUpperCase();
        int length = hex.length() / 2;
        char[] hexChars = hex.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static String bytesToHex(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString().toUpperCase();
    }

    /**
     * 把一个整形改为2位的byte数组
     * 
     * @param value
     * @return
     * @throws Exception
     */
    public static byte[] integerTo2Bytes(int value) {
        byte[] result = new byte[2];
        result[0] = (byte) ((value >>> 8) & 0xFF);
        result[1] = (byte) (value & 0xFF);
        return result;
    }

    public static byte[] integerTo1Bytes(int value) {
        byte[] result = new byte[1];
        result[0] = (byte) (value & 0xFF);
        return result;
    }

    public static String intToHex_2(int value) {
        return bytesToHex(integerTo2Bytes(value));
    }

    public static String intToHex_1(int value) {
        return bytesToHex(integerTo1Bytes(value));
    }

    public static String intToHex_4(int value) {
        return bytesToHex(integerTo4Bytes(value));
    }

    public static byte[] integerTo4Bytes(int value) {
        byte[] result = new byte[4];
        result[0] = (byte) ((value >>> 24) & 0xFF);
        result[1] = (byte) ((value >>> 16) & 0xFF);
        result[2] = (byte) ((value >>> 8) & 0xFF);
        result[3] = (byte) (value & 0xFF);
        return result;
    }

    /**
     * 获得一组十六进制串依次累加，不需要空格，累加之后取低字节
     * 
     * @param data
     * @return
     */
    public static String makeChecksum(String data) {
        if (data == null || data.equals("")) {
            return "";
        }
        int total = 0;
        int len = data.length();
        int num = 0;
        while (num < len) {
            String s = data.substring(num, num + 2);
            // System.out.println(s);
            total += Integer.parseInt(s, 16);
            num = num + 2;
        }
        /**
         * 用256求余最大是255，即16进制的FF
         */
        int mod = total % 256;
        String hex = Integer.toHexString(mod);
        len = hex.length();
        // 如果不够校验位的长度，补0,这里用的是两位校验
        if (len < 2) {
            hex = "0" + hex;
        }
        return hex.toUpperCase();
    }

    public static String makeChecksum(byte[] data) {
        if (data == null || data.length == 0) {
            return "";
        }
        int total = 0;

        for (int i = 0; i < data.length; i++) {
            int v = data[i] & 0xFF;
            total += v;
        }
        /**
         * 用256求余最大是255，即16进制的FF
         */
        int mod = total % 256;
        String hex = Integer.toHexString(mod);
        int len = hex.length();
        // 如果不够校验位的长度，补0,这里用的是两位校验
        if (len < 2) {
            hex = "0" + hex;
        }
        return hex;
    }

    public static String byteToHex(byte b) {
        int v = b & 0xFF;
        String hex = Integer.toHexString(v);
        if (hex.length() < 2) {
            hex = "0" + hex;
        }
        return hex;

    }

    public static int HexToInt(String hex, int start, int len) {

        return HexToInt(hex.substring(start, start + len));
    }

    public static int HexToInt(String hex) {
        int bi = Integer.valueOf(hex, 16);

        return bi;
    }

    public static int HexToShort(String hex, int start, int len) {

        return HexToShort(hex.substring(start, start + len));
    }

    public static int HexToShort(String hex) {
        int bi = Integer.valueOf(hex, 16);
        short a = (short) bi;

        return a;
    }

    public static long HexToLong(String hex) {
        return Long.valueOf(hex, 16);
    }

    public static String hexString2binaryString(String hexString) {
        if (hexString == null || hexString.length() % 2 != 0)
            return null;
        String bString = "", tmp;
        for (int i = 0; i < hexString.length(); i++) {
            tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));
            bString += tmp.substring(tmp.length() - 4);
        }
        return bString;
    }

    /**
     * 字符串转换成为16进制(无需Unicode编码)
     * 
     * @param str
     * @return
     */
    public static String str2HexStr(String str) {
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
            // sb.append(' ');
        }
        return sb.toString().trim();
    }

}